package com.kaisheng.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaisheng.entity.User;
import com.kaisheng.service.LoginService;
import com.kaisheng.util.StringUtil;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String code = request.getParameter("code");
		HttpSession session = request.getSession();
		session.setAttribute("code", code);
		request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		if(StringUtil.isEmpty(email)){
			response.sendRedirect("login.jspx?code=10001");
			return;
		}
		if(StringUtil.isEmpty(password)){
			response.sendRedirect("login.jspx?code=10002");
			return;
		}
		LoginService ls = new LoginService();
		User user = ls.findByEmail(email);
		if(user==null){
			response.sendRedirect("login.jspx?code=10003");
			return;
		}
		if(password.equals(user.getPassword())){
			
			HttpSession session = request.getSession();
			session.setAttribute("cur_user", user);
			
			response.sendRedirect("main.jspx");
		}else{
			response.sendRedirect("login.jspx?code=10004");
		}
		
		
	}

	
}
